package Concurrency2.Chapter02_InnerLockPrinciple;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;

import static utils.MUtils.*;

/**
 * Instruction：使用JOL工具查看锁在升级过程中的状态变化
 * JOL工具: 用于分析查看OpenJDK或HotSpot_jvm中对象的布局结构
 * Author：@author MaLi
 *
 * -Djdk.attach.allowAttachSelf     屏蔽warning
 * -XX:BiasedLockingStartupDelay=0  偏向锁开启延迟时间设置
 * -XX:-UseBiasedLocking            取消偏向锁
 * -XX:PreBlockSpin                 自旋次数设置, 默认为10次
 * -XX:+UseSpinning
 */
public class T04_JOL {
    public static void main(String[] args) throws InterruptedException {
        Object o = new Object();
        print("VMdetails: " + VM.current().details());
//        timeDelay(5);
        //打印当前锁状态
        String s = ClassLayout.parseInstance(o).toPrintable();
        print("ThreadID: " + Thread.currentThread().getId() + "-->" + Thread.currentThread().getName());
        print(s);
        print("=====================================================================================");

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                synchronized (o) {
                    //创建线程, 获取锁状态
                    String msg = ClassLayout.parseInstance(o).toPrintable();
                    print("ThreadID: " + Thread.currentThread().getId() + "-->" + Thread.currentThread().getName());
                    print(msg);
                }
            }
        }, "Thread-1");

        Thread t2 = new Thread(() -> {
            //创建线程, 获取锁状态
            for (int i = 0; i < 2; i++) {
                synchronized (o) {
                    //创建线程, 获取锁状态
                    String msg = ClassLayout.parseInstance(o).toPrintable();
                    print("ThreadID: " + Thread.currentThread().getId() + "-->" + Thread.currentThread().getName());
                    print(msg);
                }
            }
        }, "Thread-2");


        Thread t3 = new Thread(() -> {
            //创建线程, 获取锁状态
            synchronized (o) {
                //创建线程, 获取锁状态
                String msg = ClassLayout.parseInstance(o).toPrintable();
                print("ThreadID: " + Thread.currentThread().getId() + "-->" + Thread.currentThread().getName());
                print(msg);
            }
        }, "Thread-3");

        t1.start();
        t1.join(); //等待t1线程执行完成

        t2.start();//t2线程获取锁的时候, 发现偏向锁指向t1, 理论偏向锁应该进行锁撤销, 并且升级为轻量级锁

        t3.start(); //在放开t3注释的情况下, 轻量级锁发生竞争, 在默认时间范围内, 没有获取到锁, 会升级为重量级锁
        /*

        t2.join();
        t3.join();
        t3.start();
        t2.join();
        t3.join();*/

        String msg = ClassLayout.parseInstance(o).toPrintable();
        print("ThreadID: " + Thread.currentThread().getId() + "-->" + Thread.currentThread().getName());
        print(msg);
    }
}
